package controller.ur;

import java.io.File;
import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.undo.CannotUndoException;

import org.apache.log4j.Logger;

import controller.CUtil;
import controller.ur.note.SNoteSave;

import model.dao.AlbumDaoLocal;
import model.entity.Album;
import model.entity.Photo;

/**
 * Servlet implementation class SAlbumRemove
 */
public class SAlbumRemove extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private AlbumDaoLocal albumDao;
	
	private Logger log=Logger.getLogger(SAlbumRemove.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SAlbumRemove() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		
		Integer albumId=Integer.parseInt((String)request.getParameter("albumId"));
		Album album=albumDao.findById(albumId);
		Integer authorsId=album.getUser().getId();
		album.setUser(null);
		File file;
		for(Photo photo:album.getPhotos()){
			file=new File(getServletContext().getRealPath("")+photo.getLocation());
			file.delete();
			file=new File(getServletContext().getRealPath("")+photo.getThumbnailLocation());
			file.delete();
		}
		log.info("Album removed: "+album.toString());
		albumDao.remove(album);
		CUtil.redirecter(request, response, "/SAuthorsProfile?userId="+authorsId);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
